﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SAD_SiS.Models;
using System.Web.Security;
using System.Data.Entity.Validation;
using System.IO;

namespace SAD_SiS.Controllers
{
    public class AccountController : Controller
    {
        //
        // GET: /Account/
        public ActionResult Index()
        {
            return View();
        }
        public ActionResult Login(FormCollection form)
        {
            string username = form["username"];
            string password = form["password"];
            bool isRemember = Convert.ToBoolean(form["chkRemember"]);
            using (var dbContext = new SADEntities())
            {
                Account chkAcc = (from c in dbContext.Accounts
                                  where c.Username == username
                                  select c).SingleOrDefault();
                if (chkAcc == null)
                {
                    return Json(new { Success = false, Message = "Tên đăng nhập không đúng" });
                }
                if (chkAcc.Userpass.Equals(password))
                {
                    if (chkAcc.Active == true)
                    {
                        if (chkAcc.RoleID != 1)
                        {
                            if (isRemember)
                            {
                                HttpCookie cookie = new HttpCookie("login");
                                cookie.Values.Add("UserName", username);

                                cookie.Values.Add("Password", password);

                                cookie.Expires = DateTime.Now.AddDays(30);
                            }
                            if (chkAcc.RoleID == 2)
                            {
                                HttpContext.Session.Add("shop-owner", username);
                                return Json(new { Success = true, GoShop = true });
                            }
                            else
                            {
                                return Json(new { Success = true, GoAdmin = true });
                            }
                        }
                        else
                        {
                            HttpContext.Session.Add("username", username);
                            return Json(new { Success = true });
                        }
                    }
                    else
                    {
                        return Json(new { Success = false, Message = "Tài khoản đã bị block" });
                    }
                }
                else
                {
                    return Json(new { Success = false, Message = "Mật khẩu không đúng" });
                }
            }
        }

        public ActionResult GetLoginButton()
        {
            return PartialView("LoginButton");
        }
        public ActionResult LogOut()
        {
            HttpContext.Session.Add("shop-owner", "");
            return RedirectToAction("Index", "Home");
        }

        public ActionResult Profile(string strUser)
        {
            using (SADEntities dbContext = new SADEntities())
            {
                var account = (from acc in dbContext.Accounts where acc.Username.Equals(strUser) select acc).Single();
                return View(account);
            }
        }
        public ActionResult FogotPws(FormCollection form)
        {
            return View();
        }

        public ActionResult Register()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Register(HttpPostedFileBase Avatar, FormCollection form)
        {
            string username = form["Username"];
            string pwd = form["Userpass"];
            string email = form["Email"];
            string fullname = form["Fullname"];
            DateTime birthday = Convert.ToDateTime(form["Birthday"]).Date;
            string phoneNo = form["PhoneNo"];
            string street = form["Street"];
            string district = form["District"];
            var avatarName = Path.GetFileName(Avatar.FileName);
            var path = Path.Combine(Server.MapPath("~/Content/avatar/"), avatarName);

            using (SADEntities dbContext = new SADEntities())
            {
                int result = 0;
                var user = (from acc in dbContext.Accounts select acc).ToList();
                foreach (var acc in user)
                {
                    if (acc.Username.Equals(username))
                    {
                        result = 1;
                        break;
                    }
                    else if (acc.Email.Equals(email))
                    {
                        result = 2;
                        break;
                    }
                }
                if (result == 0)
                {
                    Account account = new Account();
                    Customer customer = new Customer();
                    account.Username = username;
                    account.Userpass = pwd;
                    account.Email = email;
                    account.CreatedDate = DateTime.Now;
                    account.RoleID = 3;
                    account.Active = true;
                    dbContext.Accounts.Add(account);
                    dbContext.SaveChanges();
                    customer.Username = username;
                    customer.FullName = fullname;
                    customer.BirthDate = birthday;
                    customer.Avatar = avatarName;
                    customer.Phone = phoneNo;
                    customer.Street = street;
                    customer.District = district;
                    dbContext.Customers.Add(customer);
                    dbContext.SaveChanges();
                    Avatar.SaveAs(path);

                    HttpContext.Session.Add("username", username);

                    return RedirectToAction("Index", "Home");
                }
                else if (result == 1)
                {
                    ModelState.AddModelError(string.Empty, "Tên đăng nhập đã tồn tại. Vui lòng chọn tên khác.");
                }
                else
                {
                    ModelState.AddModelError(string.Empty, "Email đã tồn tại. Vui lòng nhập email khác");
                }
                return View();
            }

        }
        public ActionResult DeliverInfor() { return View(); }
        public ActionResult RegisterShop() { return View(); }
        [HttpPost]
        public ActionResult RegisterShop(HttpPostedFileBase ShopLogo, FormCollection form)
        {
            string shopName = form["ShopName"];
            string username = form["Username"];
            string shopLink = "http://sendo.vn/shop/" + form["shopLink"];
            string slogan = form["Slogan"];
            string description = form["ShopDescription"];
            string email = form["Email"];
            string pwd = form["password"];
            string fullname = form["shopFullName"];
            string CMND = form["CMND"];
            string address = form["Address"];
            string phoneNo = form["phoneNo"];
            var shopLogoName = Path.GetFileName(ShopLogo.FileName);
            var path = Path.Combine(Server.MapPath("~/Content/ShopLogo/"), shopLogoName);
            using (SADEntities dbContext = new SADEntities())
            {
                int result = 0;
                var shops = (from s in dbContext.Shops select s).ToList();
                foreach (var shop in shops)
                {
                    if (shop.ShopName.Equals(shopName))
                    {
                        result = 1;
                        break;
                    }
                }
                var accounts = (from acc in dbContext.Accounts select acc).ToList();
                foreach (var acc in accounts)
                {
                    if (acc.Username.Equals(username))
                    {
                        result = 2;
                        break;
                    }
                    else if (acc.Email.Equals(email))
                    {
                        result = 3;
                        break;
                    }
                }
                if (result == 0)
                {
                    // thong tin chung
                    Account account = new Account();
                    Customer customer = new Customer();
                    account.Username = username;
                    account.Userpass = pwd;
                    account.Email = email;
                    account.CreatedDate = DateTime.Now;
                    account.RoleID = 2;
                    account.Active = true;
                    dbContext.Accounts.Add(account);
                    dbContext.SaveChanges();
                    // thong tin shop
                    Shop shop = new Shop();
                    shop.ShopName = shopName;
                    shop.ShopOwner = username;
                    shop.Slogan = slogan;
                    shop.LinkName=shopLink;
                    shop.Logo = shopLogoName;
                    shop.CreatedDate = DateTime.Now;
                    shop.Active = true;
                    dbContext.Shops.Add(shop);
                    dbContext.SaveChanges();
                    ShopLogo.SaveAs(path);

                    //thong tin chu shop
                    //ShopKeeper keeper = new ShopKeeper();
                    //keeper.Username = username;
                    //keeper.CMND = CMND;
                    //keeper.FullName = fullname;
                    //keeper.ContactAddress = address;
                    //keeper.Phone = phoneNo;
                    //keeper.Active = true;
                    //dbContext.ShopKeepers.Add(keeper);
                    //dbContext.SaveChanges();

                    HttpContext.Session.Add("shop-owner", username);
                    return RedirectToAction("Index","Home");
                }
                else if (result == 1)
                {
                    ModelState.AddModelError(string.Empty, "Tên shop đã tồn tại. Vui lòng chọn tên khác.");
                }
                else if (result == 2)
                {
                    ModelState.AddModelError(string.Empty, "Tên đăng nhập đã tồn tại. Vui lòng chọn tên khác.");
                }
                else
                {
                    ModelState.AddModelError(string.Empty, "Email đã tồn tại. Vui lòng nhập email khác.");
                }
                return View();
            }
        }
    }
}
